package com.aplink.generic.util;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

public class InputStreamWrapper extends BufferedInputStream {
    protected long mContentLen, mBytesLoaded;

    protected InputStreamProgressListener mProgressListener;

    public InputStreamWrapper( InputStream in, int size, long contentLen ) {
        super( in, size );
        this.mContentLen = contentLen;
        this.mBytesLoaded = 0;
    }

    @Override
    public synchronized int read( byte[] buffer, int offset, int byteCount )
            throws IOException {
        this.mBytesLoaded += byteCount;
        if ( this.mProgressListener != null ) {
            this.mProgressListener.onProgress( ( this.mBytesLoaded * 1.0f ) / this.mContentLen,
                    this.mBytesLoaded, this.mContentLen );
        }
        return super.read( buffer, offset, byteCount );
    }

    public void setProgressListener( InputStreamProgressListener listener ) {
        this.mProgressListener = listener;
    }

    public static interface InputStreamProgressListener {
        public void onProgress( float progressValue, long bytesLoaded,
                                long bytesTotal );
    }

}
